import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
import axios from 'axios'
import car from './car'

const myPlugin = store => {
  // 当 store 初始化后调用
  store.subscribe((mutation, state) => {
    // 每次 mutation 之后调用
    console.log('提交mutations');
    // mutation 的格式为 { type, payload }
    localStorage.setItem('list', JSON.stringify(state.list))
  })
}

export default new Vuex.Store({
  state: {
    list: JSON.parse(localStorage.getItem('list')) || []
  },
  getters: {
    list1(state) {
      return state.list.filter(item => item.isChecked)
    },
    list2(state) {
      return state.list.filter(item => !item.isChecked)
    }
  },
  mutations: {
    SET_LIST(state, payload) {
      state.list = payload
    },
    DELETE_LIST(state, payload) {
      state.list = state.list.filter(item => {
        return item.id !== payload
      })
    },
    ADD_LIST(state, payload) {
      state.list.push(payload)
    }
  },
  actions: {
    async GET_LIST(context) {
      const resp = await axios.get('/api/list')
      context.commit('SET_LIST', resp.data.data)
    }
  },

  modules: {
    car
  },
  plugins: [myPlugin]
})
